# -*- coding: utf_8 -*-
# @Time: 2021/12/10 15:57
# @Author: Neymar
# @Remark: 执行计划定时任务

import logging
import os
import platform
import sys
import time
import datetime

from mxsoftpy.exception import DBError

base_dir = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.insert(0, base_dir)
sys.path.insert(0, os.path.dirname(base_dir))

from model.common.Base.timed_task import TimedTaskModel
from server.common.Base.timed_task import TimedTaskServer
from utils.public.system_method import get_server_path


class PlanTimedTask(object):

    @staticmethod
    def get_zero_today():
        """
        获取明天零点时间戳
        """
        # now = datetime.datetime.now()
        # zero_today = now - datetime.timedelta(hours=now.hour, minutes=now.minute, seconds=now.second,
        #                                       microseconds=now.microsecond)
        # zero_today = time.mktime(zero_today.date().timetuple())

        return time.mktime((datetime.date.today() + datetime.timedelta(days=1)).timetuple())

    def run(self):
        """
        执行定时任务
        """
        server_path = get_server_path()
        zero_today = self.get_zero_today()
        run_exe_name = 'python.exe' if platform.system() == 'Windows' else 'python.sh'  # 判断系统来选择不同执行名
        param = TimedTaskModel(name='计划巡检任务', runtype=2, RunExeName=run_exe_name, type=2,
                               RunPath=os.path.join(server_path, 'python'),
                               starttime=zero_today,
                               parameter=os.path.join(server_path, 'webexpress', 'python',
                                                      'pyweb', 'view', 'common', 'VideoManage',
                                                      'VideoQuality', 'plan.py '),
                               purpose='selfMonitor')
        try:
            TimedTaskServer().create(**param.dict())
        except (DBError, AssertionError) as e:
            logging.error('添加一个计划巡检任务到定时任务时出错，错误详情：%s' % (str(e)))
            print('开启计划定时任务失败')
            return
        print("成功开启定时")


if __name__ == '__main__':
    """
    巡检计划每日定时生成任务
    """
    PlanTimedTask().run()
